package com.wltt.product.frfront.config;

import com.wltt.product.frfront.config.exception.RobotException;
import com.wltt.product.frfront.config.robot.WlttRobot;
import com.wltt.product.frfront.holder.RobotHolder;
import com.wltt.product.frfront.mapper.RobotLogMapper;
import com.wltt.product.frfront.mapper.RobotMapper;
import com.wltt.product.frfront.model.po.RobotPO;
import com.wltt.product.frfront.service.RobotService;
import fairino.FrLogLevel;
import fairino.FrLogType;
import fairino.ROBOT_STATE_PKG;
import fairino.Robot;
import jakarta.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RobotConfig {

    private static final Logger logger = LogManager.getLogger(RobotConfig.class);

    @Resource
    private RobotMapper robotMapper;

    @Resource
    private RobotLogMapper robotLogMapper;

    @Bean
    public WlttRobot robot() {
        RobotPO robotPO = robotMapper.queryById(1L);
        WlttRobot robot = new WlttRobot(robotMapper, robotLogMapper, robotPO);
        RobotHolder.setRobotIp(robotPO.getRobotIp());
        robot.SetReconnectParam(true, 20, 500);//设置重连次数、间隔
        robot.LoggerInit(FrLogType.DIRECT, FrLogLevel.INFO, "~/frFront/log", 10, 10);
        RobotHolder.setRobot(robot);
        int rtn = robot.RPC(RobotHolder.getRobotIp());
        if (rtn == 0) {
            RobotHolder.setRobotConnected(true);
            try {
                robot.ResetAllError();
                robot.SetSpeed(100);
                RobotHolder.setIsError(false);
            } catch (RobotException e) {
                logger.error("存在不可清除的错误信息");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            RobotHolder.setRobotConnected(false);
        }
        return robot;
    }
}
